/*
 * @Description: 
 * @Author: 张凌瑞
 * @Date: 2021-03-08 10:53:14
 * @LastEditTime: 2021-03-09 18:58:31
 * @LastEditors: 张凌瑞
 */

import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { addexam ,examUpdate} from "@/services/addexam";


export interface AddexamModelState {
  name: string;
  addexamList: { [propName: string]: any },
  questionids: string,
}
  
  export interface AddexamModelType {
    namespace: 'addexam';
    state: AddexamModelState;
    effects: {
      query: Effect;
      addexam: Effect,
      examUpdate:Effect,
    };
    reducers: {
      save: Reducer<AddexamModelState>;
      // 启用 immer 之后
      // save: ImmerReducer<IndexModelState>;
    };
    subscriptions: { setup: Subscription };
  }
  
  const AddexamModel: AddexamModelType = {
    namespace: 'addexam',
  
    state: {
      name: '',
      addexamList: {},
      questionids:'',
    },
  
    effects: {
      *query({ payload }, { call, put }) {
      },
      *addexam({ payload }, { call, put }) {
        let result = yield call(addexam, payload);
        // console.log(result)
        if (result.code === 1) {
          let aaa = result.data.questions;
          let aa = [];
          for (let i = 0; i < aaa.length; i++){
            if (aa.indexOf(aaa[i]) === -1) {
              aa.push(aaa[i].questions_id);
            }
          }
          // console.log(JSON.stringify(aa.join(",")));
          yield put({
            type: 'save',
            payload: { questionids: JSON.stringify(aa.join(",")) }
          })
        }
      },
      *examUpdate({ payload }, { call, put }) {//更新
        let result = yield call(examUpdate, payload);
        console.log(result);
        console.log(payload);

        yield put({
          type: 'save',
        })
      }
    },
    reducers: {
      save(state, action) {
        return {
          ...state,
          ...action.payload,
        };
      },
      // 启用 immer 之后
      // save(state, action) {
      //   state.name = action.payload;
      // },
    },
    subscriptions: {
      setup({ dispatch, history }) {
        return history.listen(({ pathname }) => {
          if (pathname === '/') {
            dispatch({
              type: 'query',
            })
          }
        });
      }
    }
  };
  
  export default AddexamModel;